﻿Shader "Unlit/Lambert"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _BaseColor ("Color", Color) = (1,1,1,1)
    }
    SubShader
    {
        Tags 
        {
            "RenderType" = "Opaque" 
            "RenderPipeline" = "UniversalRenderPipeline" 
        }
        LOD 100

        Pass
        {
           HLSLPROGRAM

           #pragma vertex vert
           #pragma fragment frag

           #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
           #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
           #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl"

           TEXTURE2D(_MainTex);
           SAMPLER(sampler_MainTex);

           CBUFFER_START(UnityPerMaterial)
               /*输入变量的声明要包在CBUFFER_START(UnityPerMaterial)和CBUFFER_END中*/
               half4 _BaseColor;
               float4 _MainTex_ST;
           CBUFFER_END

           struct a2v{
               //顶点着色器的输入，我们需要顶点位置和法线，语义和CG中一样
               float4 vertex : POSITION;
               half3 normal : NORMAL;
               float2 uv : TEXCOORD0;
           };

           struct v2f{
               //顶点着色器的输出
               float4 pos : SV_POSITION;
               half3 worldNormal : TEXCOORD0;
               float2 uv : TEXCOORD1;
           };

           v2f vert(a2v v)
           {
               v2f o;
               o.pos = TransformObjectToHClip(v.vertex.xyz);           //将顶点转换到裁剪空间，这步是顶点着色器必做的事情，否则渲染后模型会错位。
               o.worldNormal = TransformObjectToWorldNormal(v.normal); //将法线切换到世界空间下，注意normal是方向
               o.uv = TRANSFORM_TEX(v.uv, _MainTex);
               return o;
           }

           half4 frag(v2f i) : SV_TARGET
           {
               float4 texCol = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
               Light mlight = GetMainLight();                                  //获取主光源的数据      
               float power = saturate(dot(mlight.direction,i.worldNormal));    //计算漫反射强度
               return _BaseColor * power * half4(mlight.color,1) * texCol;              //将表面颜色，漫反射强度和光源强度混合。
           }
           ENDHLSL
        }
    }
}
